package org.java.base.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelExample {

    /**
     *   阻塞式
     * @throws IOException
     */
    public void example() throws IOException {
       ServerSocketChannel socketChannel = ServerSocketChannel.open();

        socketChannel.socket().bind(new InetSocketAddress(9999));

        while(true){
            SocketChannel channel = socketChannel.accept();

            //do something with socketChannel...
        }

    }

    /**
     *   非阻塞式
     *
     *   可以将ServerSocketChannel设置为非阻塞模式。在非阻塞模式下，accept()方法会立即返回，如果没有传入的连接到达，
     *   则可能返回null。因此，您必须检查返回的SocketChannel是否为空。下面是一个例子:
     * @throws IOException
     */
    public void example1() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        serverSocketChannel.configureBlocking(false);

        while(true){
            SocketChannel socketChannel =
                serverSocketChannel.accept();

            if(socketChannel != null){
                //do something with socketChannel...
            }
        }
    }
}
